package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.ConsumerLocation;
import com.mingqijia.gassafety.db.entity.Contacts;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.db.entity.vo.OperationLogVO;
import com.mingqijia.gassafety.db.mapper.ContactsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.shared.constant.OperationTypeEnum;
import com.mingqijia.gassafety.shared.constant.TableConst;
import com.mingqijia.gassafety.webserver.request.ContactsEditRequest;
import com.mingqijia.gassafety.webserver.request.ContactsRequest;
import com.mingqijia.gassafety.webserver.service.ContactsService;
import com.mingqijia.gassafety.webserver.service.OperationLogService;
import com.mingqijia.gassafety.shared.log.LogRecord;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.OperateRecordEnum.*;

/**
 * <p>
 * 客户留存的联系人表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-02-22
 */
@Service
public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts> implements ContactsService {

    @Autowired
    ContactsMapper contactsMapper;

    @Autowired
    OperationLogService operationLogService;

    @Override
    public List<Contacts> listByIds(List<Integer> ids, String spId) {
        return contactsMapper.highestListByIds( ids,spId );
    }

    @Override
    public List<Map<String, Object>> selectInfo(String consumerId) {
        return contactsMapper.selectInfo(consumerId);
    }

    @Override
    @LogRecord(operateType = OPERATE_TYPE_5, consumerId = "#contacts.consumerId",
            detail = "new com.mingqijia.gassafety.webserver.utils.LogUtil().addOrDeleteEntity(#contacts, T(com.mingqijia.gassafety.db.entity.Contacts))")
    public void addContacts(Contacts contacts) {
        this.save(contacts);

        //操作日志log-14
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_14.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.t_gss_contacts.name());
        logVO.setTableKey(contacts.getId().toString());
        operationLogService.insertLog(logVO);
    }

    @Override
    @LogRecord(operateType = OPERATE_TYPE_7, consumerId = "#consumerId",
            detail = "new com.mingqijia.gassafety.webserver.utils.LogUtil().addOrDeleteEntity(#contacts, T(com.mingqijia.gassafety.db.entity.Contacts))")
    public void deleteContacts(Integer consumerId, Contacts contacts) {
        //该联系人被删除
        Contacts contactsNew = new Contacts();
        contactsNew.setId(contacts.getId());
        contactsNew.setIsDeleted(true);
        this.updateById(contactsNew);
        //操作日志log-13
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_13.getCode());
        logVO.setTableName(TableConst.t_gss_contacts.name());
        logVO.setTableKey(contacts.getId().toString());
        logVO.setCodeList(logCodeList);
        operationLogService.insertLog(logVO);
    }

    @Override
    public void updateContacts(Integer id) {
        Contacts contactsNew = new Contacts();
        contactsNew.setId(id);
        contactsNew.setIsDeleted(true);
        this.updateById(contactsNew);
    }

    @Override
    public void addUpdateContacts(Consumer consumer) {
        try {
            QueryWrapper<Contacts> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Contacts::getConsumerId, consumer.getId());
            queryWrapper.lambda().eq(Contacts::getLevel, 99);
            queryWrapper.lambda().eq(Contacts::getIsDeleted, 0);
            List<Contacts> contactsList = contactsMapper.selectList(queryWrapper);
            if (contactsList.size() > 0) {
                Contacts contact = contactsList.get(0);
                if (StringUtils.isNotEmpty(consumer.getName())) {
                    contact.setName(consumer.getName());
                }
                contact.setTelephone(consumer.getPhone());
                contactsMapper.updateById(contact);
            } else {
                Contacts contact = new Contacts();
                contact.setConsumerId(consumer.getId());
                contact.setTelephone(consumer.getPhone());
                contact.setLevel(99);
                contact.setRemark("时刻家会员");
                if (StringUtils.isNotEmpty(consumer.getName())) {
                    contact.setName(consumer.getName());
                } else {
                    contact.setName("时刻家会员");
                }
                contact.setIsDeleted(consumer.getIsDeleted());
                contact.setSpId(consumer.getSpId());
                contactsMapper.insert(contact);
            }
        }catch (Exception e){
            log.error("同步更新t_gss_contacts表失败",e);
        }
    }

    @Override
    public List<Contacts> selectConsumerId(Integer consumerId) {
        QueryWrapper<Contacts> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Contacts::getConsumerId, consumerId);
        queryWrapper.lambda().eq(Contacts::getIsDeleted, 0);
        List<Contacts> contactsList = contactsMapper.selectList(queryWrapper);
        return contactsList;
    }

    @Override
    @LogRecord(operateType = OPERATE_TYPE_6, consumerId = "#contactsNew.consumerId")
    public void editContacts(Contacts contactsNew, Contacts contacts) {
            //企业级操作日志
            LogVO vo = new LogVO();
            vo.setDetail(LogUtil.compareEntity(contactsNew, contacts, Contacts.class));
            LogRecordAspect.threadLocal.set(vo);
    }

    /**
     * 批量获取客户联系人
     * @param consumerIds
     * @param spId
     * @return
     */
    @Override
    public Map<Integer,List<Contacts>> getContacts(List<Integer> consumerIds, String spId) {
        LambdaQueryWrapper<Contacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(Contacts::getSpId,spId).eq(Contacts::getIsDeleted,0)
                .in(Contacts::getConsumerId,consumerIds);
        List<Contacts> contacts = contactsMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(contacts))  return null;
        return contacts.stream()
                .collect(Collectors.groupingBy(Contacts::getConsumerId, Collectors.toList()));
    }
}
